package com.bookshop.controller;

import com.bookshop.model.UserModel;
import com.bookshop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @RequestMapping("")
    public String login(){
        return "/WEB-INF/view/login.jsp";
    }
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String findUser(Model model, String username, String userpass, HttpServletRequest request){
        UserModel userModel = userService.findByUser(username);
        if(userModel == null){
            model.addAttribute("message","用户名不存在,请注册");
            return "/WEB-INF/view/reg.jsp";
        }else{
            if(userModel.getPassWord().equals(userpass)){
                request.getSession().setAttribute("username",userModel.getUserName());
                request.getSession().setAttribute("userid",userModel.getUserId());
                model.addAttribute("user",userModel);
                return "/index";

            }else{
                model.addAttribute("message","用户名或者密码错误");
                return "/WEB-INF/view/login.jsp";
            }
        }

    }
    @RequestMapping("reg1")
    public String reg(){
        return "/WEB-INF/view/reg.jsp";
    }

    @RequestMapping(value = "reg",method = RequestMethod.POST)
    public String addUser(Model model,String username,String userpass,String gender,String age){
        UserModel userModel = userService.findByUser(username);
        if(userModel != null){
            model.addAttribute("message","用户名已经存在,请登录");
            return "/WEB-INF/view/login.jsp";
        }
        UserModel userModel1 = new UserModel();
        userModel1.setUserName(username);
        userModel1.setPassWord(userpass);
        userModel1.setAge(Integer.valueOf(age));
        userModel1.setGender(gender);
        int i = userService.addUser(userModel1);
        if(i>0){
            model.addAttribute("message","用户名已经注册,请登录");
            return "/WEB-INF/view/login.jsp";
        }else{
            model.addAttribute("message","用户名注册失败");
            return "/WEB-INF/view/reg.jsp";
        }

    }
    @RequestMapping("logout")
    public String logout(){
        return "/";
    }

    @RequestMapping("editUser")
    public String editUser(UserModel userModel,Model model){
        userService.editUser(userModel);
        model.addAttribute("user",userModel);
        return "/index";
    }
}
